<?php
namespace Asset\Controller;
use Common\Controller\AdminbaseController;
class DeviceController extends AdminbaseController {
	protected $device_model,$susers_model,$region_model;
	function _initialize() {
		parent::_initialize();
		$this->store_model = D("Store");
		$this->device_model = D("Device");
		$this->susers_model = D("Susers");
		$this->region_model = D("Region");
        $this->backup_path = '/data/';
	}
    private function devicestatus() {
		$devicestatus =
		array(
			array(
		        'ALL' => array('name' => '请选择'),
		        'ZX' => array('id' => 'ZX','name' => '二代保温箱'),
		        'MX' => array('id' => 'MX','name' => '三代保温箱'),
		        'FX' => array('id' => 'FX','name' => '四代保温箱'),
		        'AD' => array('id' => 'AD','name' => '广告机'),
		        'TA' => array('id' => 'TA','name' => '游戏桌'),
		        'OS' => array('id' => 'OS','name' => '外置摇一摇'),
		        'CS' => array('id' => 'CS','name' => '影院摇一摇'),
		        'CM' => array('id' => 'CM','name' => '自动咖啡机'),
		        'GK' => array('id' => 'GK','name' => '工卡'),
		        'QT' => array('id' => 'QT','name' => '其他设备')
	        ),
	        array(
	            '0'=>array('id' => '0', 'name'=>'请选择'),
	            '1'=>array('id' => '1', 'name'=>'停用'),
	            '2'=>array('id' => '2', 'name'=>'激活'),
	            '3'=>array('id' => '3', 'name'=>'损坏'),
	            '4'=>array('id' => '4', 'name'=>'发货'),
	            '5'=>array('id' => '5', 'name'=>'入库'),
	            '6'=>array('id' => '6', 'name'=>'出场'),
	        ),
	        array(
	            '0'=>array('id' => '0', 'name'=>'请选择'),
	            '1'=>array('id' => '1', 'name'=>'条形码'),
	            '2'=>array('id' => '2', 'name'=>'设备ID'),
	            '3'=>array('id' => '3', 'name'=>'设备UUID'),
	            '4'=>array('id' => '4', 'name'=>'major值'),
	            '5'=>array('id' => '5', 'name'=>'minor值'),
	        ),
	        array(
				'0'=>array('name'=>'请选择'),
				'100'=>array('id'=>'100','name'=>'电影院'),
				'105'=>array('id'=>'105','name'=>'私人影吧'),
				'110'=>array('id'=>'110','name'=>'奶茶/水吧'),
				'120'=>array('id'=>'120','name'=>'商超'),
				'125'=>array('id'=>'125','name'=>'KTV'),
				'130'=>array('id'=>'130','name'=>'便利店'),
				'135'=>array('id'=>'135','name'=>'烘培蛋糕店'),
				'140'=>array('id'=>'140','name'=>'西餐厅/中餐厅'),
				'150'=>array('id'=>'150','name'=>'咖啡/甜品店'),
				'160'=>array('id'=>'160','name'=>'酒吧/夜店'),
				'170'=>array('id'=>'170','name'=>'小吃店/零食店'),
				'180'=>array('id'=>'180','name'=>'网咖/网吧'),
				'190'=>array('id'=>'190','name'=>'主题公园/景区'),
				'200'=>array('id'=>'200','name'=>'副食品店'),
				'500'=>array('id'=>'500','name'=>'其他'),
			)
		);
		return $devicestatus;
    }
	function index(){
		$this->_lists();
		$this->display();
	}
	function _lists(){
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('barcode'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('devid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('uuid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==4){$search[] = array('major'=>array('like',"%$keyword%"));}
			if(I('param.search') ==5){$search[] = array('minor'=>array('like',"%$keyword%"));}
            if(I('param.dtype')){
            	$dtype =I('param.dtype');
                $search[] = array('dtype'=>$dtype);
            }
            if(I('param.status')){
        		$status =I('param.status');
                $search[] = array('status'=>$status);
            }
            if(I('param.start_time')){
                    $search[] = array('date(updatetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(updatetime)'=>array('elt',I('param.end_time')));
            }
            $_GET['dtype'] = I('param.dtype');
            $_GET['status'] = I('param.status');
			$_GET['search']=I('param.search');
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}
		if(!$search){
            $search = array('status'=>2);
            $_GET['status'] = 2;
		}

		$count=$this->device_model->where($search)->count();
		$page = $this->page($count,50);
		$devices=$this->device_model->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")->select();
		if($devices){
			foreach($devices as $device){
				$store_id[] = $device['store_id'];
			}
			if($store_id){
				$stores=$this->store_model->where(array('osid'=>array('in',$store_id)))->select();
				$this->assign("stores", $stores);
			}
		}

		$bstatus = $this->devicestatus();
		$this->assign("dtype", $bstatus[0]);
		$this->assign("bstatus", $bstatus[1]);
		$this->assign("search", $bstatus[2]);
		$this->assign("stype", $bstatus[3]);
    	$this->assign('page', $page->show('Admin'));
		$this->assign("devices", $devices);
		$this->assign("count", $count);
	}
	public function add(){
		$bstatus = $this->devicestatus();
		$this->assign("dtype", $bstatus[0]);
		$this->assign("bstatus", $bstatus[1]);
		$this->assign("stype", $bstatus[3]);
		$this->display();
	}
	public function add_post(){
		if (IS_POST) {
			if(!I("post.barcode")){
				$this->error("作为唯一标识，条形码必须输入");
			}
			$machine = $this->machine_expl();
			foreach($machine as $expl){
				if($expl['type']==substr(I("post.barcode"),0,2)){
					$_POST['dtype'] = $expl['type'];
					$remark = $this->remark($expl['type'],substr(I("post.barcode"),2,4));
				}
			}
			if(!I("post.remark")){
				$_POST['remark'] = $remark;
			}
			$device = $this->device_model->where(array('barcode'=>I("post.barcode")))->find();
			if($device){
				$this->error("此条形码已存在");
			}
			if ($this->device_model->add($_POST)) {
				$this->success("添加成功！",U('Device/index'));
			} else {
				$this->error("添加失败！");
			}
		}
	}
	public function edit(){
		$device = $this->device_model->where(array('id'=>I("get.id")))->find();
		$store = $this->store_model->where(array('store_id'=>$device['store_id']))->find();
		$oid[0]=$store['user_id'];
		$oid[1]=$store['owner_id'];
		$oid[2]=$store['agency_id'];
		$oid[3]=$store['marketing_id'];
		$oid[4]=$store['sign_user_id'];
		$susers = $this->susers_model->where(array('oid'=>array('in',$oid)))->select();
		$code[0]=$store['province_id'];
		$code[1]=$store['city_id'];
		$code[2]=$store['district_id'];
		$region = $this->region_model->where(array('code'=>array('in',$code)))->select();
		$bstatus = $this->devicestatus();
		$this->assign("device", $device);
		$this->assign("store", $store);
		$this->assign("susers", $susers);
		$this->assign("region", $region);
		$this->assign("btype", $bstatus[0]);
		$this->assign("bstatus", $bstatus[1]);
		$this->assign("stype", $bstatus[3]);
		$this->assign("urlimg", C('IMG_PATH'));
		$this->display();
	}
	public function edit_post(){
		if (IS_POST) {
			$machine = $this->machine_expl();
			foreach($machine as $expl){
				if($expl['type']==substr(I("post.barcode"),0,2)){
					$_POST['dtype'] = $expl['type'];
					$remark = $this->remark($expl['type'],substr(I("post.barcode"),2,4));
				}
			}
			if(!I("post.remark")){
				$_POST['remark'] = $remark;
			}
			if ($this->device_model->where(array('id'=>I("post.did")))->save($_POST)) {
				$this->success("更新成功！",U('Device/index'));
			} else {
				$this->error("更新失败！");
			}
		}
	}

	public function remove_loding(){
    	if (I("get.id")) {
    		$device = $this->device_model->where(array('id'=>I("get.id")))->find();
    		if ($this->device_model->where(array('id'=>I("get.id")))->setField('loding','')) {
    			if(!$this->device_model->where(array('loding'=>$device['loding']))->find()){
					$Aliyun = new \Aliyun\Controller\AliyunController();
					$Aliyun->delete($device['loding']);
    			}
    			$this->success("Loding图移除成功！");
    		} else {
    			$this->error('Loding图移除失败！');
    		}
    	} else {
			$this->error($this->device_model->getError());
    	}
	}
	public function getArr( $file ){
        if(!file_exists( $file )){
            return false;//判断文件是否存在
        }
        $arr = file($file);
        $res = array();
        foreach($arr as $value){
            $value = trim( $value );
            if( empty($value)){
                continue;//去除空行
            }
			$value=explode(",", str_replace(array("\r\n", "\r", "\n","\"","\'","，","。"), "", $value));
			$res[] = $value;//确定第二维度
		}
        return $res;
    }
	function expChangeCode($data){
		$encode = mb_detect_encoding($data, array("ASCII",'UTF-8','GB2312',"GBK",'BIG5'));
		if($encode=="UTF-8"){
		        return $data;
		}else{
				$data = eval('return '.iconv('gbk','utf-8',var_export($data,true)).';');
		        return $data;
		}
    }
	public function machine_expl(){
		$expl = array(
			array('id'=>5,'type'=>'ZX','name'=>'II代保温箱'),
			array('id'=>1,'type'=>'MX','name'=>'III代保温箱'),
			array('id'=>2,'type'=>'AD','name'=>'广告机'),
			array('id'=>3,'type'=>'TA','name'=>'游戏娱乐桌'),
			array('id'=>4,'type'=>'CM','name'=>'自动咖啡机'),
			array('id'=>6,'type'=>'QT','name'=>'其他设备'),
			array('id'=>7,'type'=>'FX','name'=>'IV代保温箱'),
			array('id'=>8,'type'=>'OS','name'=>'外置摇一摇设备'),
			array('id'=>9,'type'=>'CS','name'=>'影院摇一摇设备'),
		);
		return $expl;
	}
	public function remark($type,$length){
		$remarks = array(
			array(//'type'=>'ZX',
				array(
					array('size'=>'0','name'=>'未定义'),
				),
				array(
					array('size'=>'0','name'=>'未定义'),
				)
			),
			array(//'type'=>'MX',
				array(
					array('size'=>'1','name'=>'无屏工程机'),
					array('size'=>'2','name'=>'无屏样机'),
					array('size'=>'3','name'=>'无屏量产机'),
					array('size'=>'4','name'=>'无屏次品'),
					array('size'=>'5','name'=>'无屏翻新机'),
					array('size'=>'6','name'=>'有屏工程机'),
					array('size'=>'7','name'=>'有屏样机'),
					array('size'=>'8','name'=>'有屏量产机'),
					array('size'=>'9','name'=>'有屏次品'),
					array('size'=>'0','name'=>'有屏翻新机'),
				),
				array(
					array('size'=>'1','name'=>'有Ibeacon紫'),
					array('size'=>'2','name'=>'有Ibeacon白'),
					array('size'=>'3','name'=>'以后再定'),
					array('size'=>'4','name'=>'以后再定'),
					array('size'=>'5','name'=>'以后再定'),
					array('size'=>'6','name'=>'无Ibeacon紫'),
					array('size'=>'7','name'=>'无Ibeacon白'),
				)
			),
			array(//'type'=>'AD',
				array(
					array('size'=>'430','name'=>'43吋'),
					array('size'=>'180','name'=>'18吋'),
				),
				array(
					array('size'=>'1','name'=>'工程机'),
					array('size'=>'2','name'=>'样机'),
					array('size'=>'3','name'=>'量产机'),
					array('size'=>'4','name'=>'次品'),
					array('size'=>'5','name'=>'翻新机'),
				)
			),
			array(//'type'=>'CM',
				array(
					array('size'=>'0','name'=>'未定义'),
				),
				array(
					array('size'=>'0','name'=>'未定义'),
				)
			),
			array(//'type'=>'QT',
				array(
					array('size'=>'0','name'=>'未定义'),
				),
				array(
					array('size'=>'0','name'=>'未定义'),
				)
			),
			array(//'type'=>'FX',
				array(
					array('size'=>'0','name'=>'未定义'),
				),
				array(
					array('size'=>'0','name'=>'未定义'),
				)
			),
			array(//'type'=>'TA',
				array(
					array('size'=>'0','name'=>'未定义'),
				),
				array(
					array('size'=>'0','name'=>'未定义'),
				)
			),
			array(//'type'=>'OS',
				array(
					array('size'=>'0','name'=>'未定义'),
				),
				array(
					array('size'=>'0','name'=>'未定义'),
				)
			),
			array(//'type'=>'CS',
				array(
					array('size'=>'0','name'=>'未定义'),
				),
				array(
					array('size'=>'0','name'=>'未定义'),
				)
			),
		);
		if($type == 'ZX'){
			$remar ='II代保温箱未定义';
		}
		if($type == 'MX'){
			$type1 =substr($length,0,1);
			$type2 =substr($length,1,1);
			foreach($remarks[1][0] as$remark){
				if($remark['size']==$type1){
					$remar =$remark['name'];
				}
			}
			foreach($remarks[1][1] as$remark){
				if($remark['size']==$type2){
					$remar = $remar.'-'.$remark['name'];
				}
			}
		}
		if($type == 'AD'){
			$type1 =substr($length,0,3);
			$type2 =substr($length,3,1);
			foreach($remarks[3][0] as$remark){
				if($remark['size']==$type1){
					$remar =$remark['name'];
				}
			}
			foreach($remarks[3][1] as$remark){
				if($remark['size']==$type2){
					$remar = $remar.'-'.$remark['name'];
				}
			}
		}
		if($type == 'CM'){
			$remar ='自动咖啡机未定义';
		}
		if($type == 'QT'){
			$remar ='其他未知设备';
		}
		if($type == 'FX'){
			$remar ='四代保温箱';
		}
		if($type == 'TA'){
			$remar ='游戏娱乐桌';
		}
		if($type == 'OS'){
			$remar ='外置摇一摇设备';
		}
		if($type == 'CS'){
			$remar ='影院摇一摇设备';
		}
		return $remar;
	}
	public function inputcsv(){
		$this->display();
	}
	public function inputcsv_post(){
			if(!I('post.filetype')){
				$this->error("请选择文件类型");
			}
			if($_FILES["inputcsv"]["size"]<1){
				$this->error("请选择文件");
			}
			setlocale(LC_ALL, 'en_US.UTF-8');
			if($_FILES["inputcsv"]["name"]){
					$path1 = $_FILES["inputcsv"]["name"];
					$path2 =time().substr($path1,strpos($path1,'.'));
				if(substr($path1,strpos($path1,'.'))!='.csv'){
				   	$this -> error('文件格式不正确');
				}
			}
			if($_FILES["inputcsv"]["size"]>512000){
			   	$this -> error('文件大小不得超过512KB');
			}
			move_uploaded_file($_FILES["inputcsv"]["tmp_name"],RUNTIME_PATH.$path2);

			$file = RUNTIME_PATH.$path2;
			$arr = $this->getArr($file);
			if((I('post.filetype')==1 && count($arr[0]) != 18) || (I('post.filetype')==2 && count($arr[0]) != 6) || (I('post.filetype')==3 && count($arr[0]) != 5)){
					$this->error('文件内容与所选类型不匹配');
			}
			$carr =count($arr);
			if($carr >=2000){
			   	$this -> error('文件内容过多，请拆分文件导入');
			}
			if(I('post.filetype')==1){
				$ca = count($arr[0]);
				for($i=2;$i<$carr;$i++){
					$str=$store=null;
					for($j=0;$j<$ca;$j++){
						$str[] = $this->expChangeCode($arr[$i][$j]);
					}
					$store['store_id'] = $str[0];
					$store['title'] = $str[1];
					$store['title_branch'] = $str[2];
					$store['address'] = $str[3];
					$store['add_time'] = $str[4];
					$store['longitude'] = $str[5];
					$store['latitude'] = $str[6];
					$store['province_id'] = $str[7];
					$store['city_id'] = $str[8];
					$store['district_id'] = $str[9];
					$store['stype'] =$str[10];
					$store['status'] = $str[11];
					$store['zzb_id'] = $str[12];
					$store['user_id'] = $str[13];
					$store['owner_id'] = $str[14];
					$store['agency_id'] = $str[15];
					$store['marketing_id'] = $str[16];
					$store['sign_user_id'] = $str[17];
					if($this->store_model->where(array('store_id'=>$str[0]))->find()){
						$this->store_model->where(array('store_id'=>$str[0]))->save($store);
					}else{
						$this->store_model->add($store);
					}
				}
			}
			if(I('post.filetype')==2){
				$ca = count($arr[0]);
				for($i=1;$i<$carr;$i++){
					$str=$device=null;
					for($j=0;$j<$ca;$j++){
						$str[] = $this->expChangeCode($arr[$i][$j]);
					}
					$machine = $this->machine_expl();
					foreach($machine as $expl){
						if($expl['type']==substr($str[0],0,2)){
							$type = $expl['type'];
							$remark = $this->remark($expl['type'],substr($str[0],2,4));
						}
					}

					$device['barcode'] = $str[0];
					$device['devid'] = $str[1];
					$device['uuid'] = $str[2];
					$device['major'] = $str[3];
					$device['minor'] = $str[4];
					$device['store_id'] = $str[5];
					$device['dtype'] = $type;
					$device['status'] = 4;
					$device['remark'] = $remark;
					if($this->device_model->where(array('barcode'=>$str[0]))->find()){
						$this->device_model->where(array('barcode'=>$str[0]))->save($device);
					}else{
						$this->device_model->add($device);
					}
				}
			}
			if(I('post.filetype')==3){
				$ca = count($arr[0]);
				for($i=1;$i<$carr;$i++){
					$str=$susers=null;
					for($j=0;$j<$ca;$j++){
						$str[] = $this->expChangeCode($arr[$i][$j]);
					}
					$susers['oid'] = $str[0];
					$susers['realname'] = $str[1];
					$susers['mobile'] = $str[2];
					$susers['sex'] = $str[3];
					$susers['password'] = $str[4];
					if($this->susers_model->where(array('oid'=>$str[0]))->find()){
						$this->susers_model->where(array('oid'=>$str[0]))->save($susers);
					}else{
						$this->susers_model->add($susers);
					}
				}
			}
			fclose($file);
			$this->success("设备信息更新成功！");
	}
    /**
     * 下载文件
     */
    public function download(){
        $backup_name = isset($_GET['backup']) && trim($_GET['backup']) ? trim($_GET['backup']) :
            $this->error('请选择文件名称！');
        $file = isset($_GET['file']) && trim($_GET['file']) ? trim($_GET['file']) : $this->
            error('请选择文件文件！');
        $sql_file = SITE_PATH . $this->backup_path . $backup_name . '/' . $file;
        if (file_exists($sql_file)){
            header('Content-type: application/unknown');
            header('Content-Disposition: attachment; filename="' . $file . '"');
            header("Content-Length: " . filesize($sql_file) . "; ");
            readfile($sql_file);
        }else{
            $this->error('文件不存在！');
        }
    }
	public function export_csv($filename, $data){
		$file_hwnd=fopen('data/runtime/'.$filename,"w");
		header("Content-type:text/csv");
		header("Content-Disposition:attachment;filename=".$filename);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		fwrite($file_hwnd,$data);
		fclose($file_hwnd);
	}
    public function outcsv(){
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('barcode'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('devid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('uuid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==4){$search[] = array('major'=>array('like',"%$keyword%"));}
			if(I('param.search') ==5){$search[] = array('minor'=>array('like',"%$keyword%"));}
            if(I('param.btype')){
            	$btype =I('param.btype');
                $search[] = array('btype'=>$btype);
            }
            if(I('param.status')){
        		$status =I('param.status');
                $search[] = array('status'=>$status);
            }
            if(I('param.start_time')){
                    $search[] = array('date(updatetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(updatetime)'=>array('elt',I('param.end_time')));
            }
		}
		if(!I('param.btype') && !I('param.status') && !I('param.search') && !I('param.keyword') && !I('param.start_time') && !I('param.end_time')){
		    $this->error('请选择查询条件！');
		}
		$device=$this->device_model->where($search)->select();
		if(count($device) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$bstatus = $this->devicestatus();
		$head[] = iconv('utf-8','GBK',",SN码,设备ID,UUID,Major,Minor,店铺名称,店铺子名称,店铺地址,店铺类型,省,市,区\r\n");
		if($device){
			set_time_limit(0);
			foreach($device as $dev){
				$store = $this->store_model->where(array('store_id'=>$dev['store_id']))->find();
				if($store['province_id'] && $store['city_id'] && $store['district_id']){
					$province = $this->region_model->where(array('code'=>$store['province_id']))->find();
					$city = $this->region_model->where(array('code'=>$store['city_id']))->find();
					$district = $this->region_model->where(array('code'=>$store['district_id']))->find();
				}else{
					$province['name'] = '中国';
					$city['name'] = '';
					$district['name'] = '';
				}
				$content[] = iconv('utf-8','GBK',$dev['barcode']).",".
						iconv('utf-8','GBK',$dev['devid']).",".
						iconv('utf-8','GBK',$dev['uuid']).",".
						iconv('utf-8','GBK',$dev['major']).",".
						iconv('utf-8','GBK',$dev['minor']).",".
						iconv('utf-8','GBK',$store['title']).",".
						iconv('utf-8','GBK',$store['title_branch']).",".
						iconv('utf-8','GBK',$store['address']).",".
						iconv('utf-8','GBK',$bstatus[3][$store['stype']]['name']).",".
						iconv('utf-8','GBK',$province['name']).",".
						iconv('utf-8','GBK',$city['name']).",".
						iconv('utf-8','GBK',$district['name'])."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Device/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }
}
